import pymysql


class DBUtils:
    count = -1

    def __init__(self):
        try:
            self.conn = pymysql.connect(
                host='192.168.10.130',
                port=3306,
                user='root',
                password='123456',
                db='wms'
            )
            self.cursor = self.conn.cursor()
            print("数据库连接成功！")
        except Exception as e:
            print(e)
            print("数据库连接失败！")

    def close(self):
        self.cursor.close()
        self.conn.close()

    def find_one(self, sql, params=None):
        self.conn.commit()
        try:
            if params is None:
                self.cursor.execute(sql)
            else:
                self.cursor.execute(sql, params)
            return self.cursor.fetchone()
        except Exception as e:
            print("查询单条数据失败",e)

    def find_all(self, sql, params=None):
        self.conn.commit()
        try:
            if params is None:
                self.cursor.execute(sql)
            else:
                self.cursor.execute(sql, params)
            return self.cursor.fetchall()
        except Exception as e:
            print("查询多条数据失败",e)

    def find_count(self, sql, params=None):
        self.conn.commit()
        try:
            if params is None:
                self.cursor.execute(sql)
            else:
                self.cursor.execute(sql, params)
            return self.cursor.rowcount
        except Exception as e:
            print("查询条目数",e)

    def cud(self,sql, params=None):
        self.conn.commit()
        try:
            if params is None:
                self.count = self.cursor.execute(sql)
            if isinstance(params, list):
                self.count = self.cursor.executemany(sql, params)
            if isinstance(params, tuple):
                self.count = self.cursor.execute(sql, params)
            self.conn.commit()
            return self.count
        except Exception as e:
            print("增删改失败",e)
